package com.inossem.allotin.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.inossem.allotin.R;
import com.inossem.allotin.db.CacheBean;
import com.inossem.allotin.utils.GreenDaoManager;
import com.inossem.allotin.activity.bluetooth.BlueToothBaseActivity;
import com.inossem.allotin.activity.bluetooth.BluetoothListActivity;
import com.inossem.allotin.adapter.EmergencyListAdapter;
import com.inossem.allotin.adapter.ReceiptTypeAdapter;
import com.inossem.allotin.utils.requestUtils.RetrofitUtils;
import com.inossem.wms.model.cus.CusRealWh;
import com.inossem.wms.vo.BaseObject;
import com.inossem.wms.vo.cus.CusRFIDEmergency;
import com.inossem.wms.vo.cus.CusRFIDTaskReqVo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Response;

public class EmergencyListActivity extends BlueToothBaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;//列表

    @BindView(R.id.cb_check)
    CheckBox cbCheck;
    @BindView(R.id.tv_receipt_type)
    TextView tvReceiptType;
    @BindView(R.id.ll_recepit_type)
    LinearLayout llRecepitType;
    @BindView(R.id.tv_work_location)
    TextView tvWorkLocation;
    @BindView(R.id.ll_work_location)
    LinearLayout llWorkLocation;
    @BindView(R.id.tv_information_1)
    TextView tvInformation1;
    @BindView(R.id.include_no_data)
    LinearLayout includeNoData;

    private EmergencyListAdapter adapter;
    //前序单据类型
    private List<com.inossem.allotin.bean.TrayReceiptTypeBean> listReceipt = new ArrayList<>();
    //实体仓库
    private List<CusRealWh> list = new ArrayList<>();
    private String mWhCode;
    private String mWhName;
    private Integer mReceiptType;
    private String mReceiptTypeName;
    //缓存数据
    private List<CacheBean> mCacheBeanList = new ArrayList<>();
    private GreenDaoManager mGreenDaoManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_emergency_list);
        ButterKnife.bind(this);
        initView();
        initData();
        applyPermission();
    }

    public void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        listReceipt = com.inossem.allotin.utils.PickUtils.initDown(this);
        tvReceiptType.setText(listReceipt.get(0).getReceiptName());
        mReceiptType = listReceipt.get(0).getReceiptCode();
        mReceiptTypeName = listReceipt.get(0).getReceiptName();
        listReceipt.get(0).setCheck(true);

        CusRealWh bean1 = new CusRealWh();
        bean1.setCusWhSys("JDW1");
        bean1.setCusWhName("W1仓库");
        bean1.setClick(true);
        CusRealWh bean2 = new CusRealWh();
        bean2.setCusWhSys("JDW2");
        bean2.setCusWhName("W2仓库");
        CusRealWh bean3 = new CusRealWh();
        bean3.setCusWhSys("JDW3");
        bean3.setCusWhName("W3仓库");
        CusRealWh bean4 = new CusRealWh();
        bean4.setCusWhSys("JDW4");
        bean4.setCusWhName("W4仓库");
        CusRealWh bean5 = new CusRealWh();
        bean5.setCusWhSys("JDW5");
        bean5.setCusWhName("W5仓库");
        CusRealWh bean6 = new CusRealWh();
        bean6.setCusWhSys("JDW6");
        bean6.setCusWhName("W6仓库");
        CusRealWh bean7 = new CusRealWh();
        bean7.setCusWhSys("JDW7");
        bean7.setCusWhName("W7仓库");
        CusRealWh bean8 = new CusRealWh();
        bean8.setCusWhSys("JDW8");
        bean8.setCusWhName("W8仓库");
        list.add(bean1);
        list.add(bean2);
        list.add(bean3);
        list.add(bean4);
        list.add(bean5);
        list.add(bean6);
        list.add(bean7);
        list.add(bean8);
        mWhCode = list.get(0).getCusWhSys();
        mWhName = list.get(0).getCusWhName();
        tvWorkLocation.setText(list.get(0).getCusWhSys() + "-" + list.get(0).getCusWhName());
    }

    public void initData() {
        //默认不弹出键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //强制横屏z
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        GreenDaoManager.getInstance().init(EmergencyListActivity.this);
        mGreenDaoManager = GreenDaoManager.getInstance();
        adapter = new EmergencyListAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.setListener(new EmergencyListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int i) {
                Intent intent = new Intent(EmergencyListActivity.this, EmergencyDetailActivity.class);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.STATUS_CODE, com.inossem.allotin.constant.ItemStatusConstant.STATUS_COMPLETED);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.CUS_WH_SYS, mWhCode);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.CUS_WH_NAME, mWhName);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.RECEIPT_TYPE, mReceiptType);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.RECEIPT_TYPE_NAME, mReceiptTypeName);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.DATA, mCacheBeanList.get(i));
                startActivity(intent);
            }

            @Override
            public void onFileClick(int position) {
                if (mCacheBeanList.get(position).getFileName().equals("点击生成文件")) {
                    getFile(position);
                } else {
                    openFile(mCacheBeanList.get(position).getFilePath());
                }
            }

            @Override
            public void onCheck(boolean isCheck) {
                cbCheck.setChecked(isCheck);
            }
        });
        GreenDaoManager.getInstance().init(EmergencyListActivity.this);
    }

    //生成文件
    private void getFile(int position) {
        List<CusRFIDTaskReqVo> list = new Gson().fromJson(mCacheBeanList.get(position).getJsonList(), new TypeToken<List<CusRFIDTaskReqVo>>() {
        }.getType());
        List<CusRFIDEmergency> listCo = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CusRFIDEmergency cusRFIDEmergency = new CusRFIDEmergency();
            cusRFIDEmergency.setReceiptCode(mCacheBeanList.get(position).getReceiptCode());
            cusRFIDEmergency.setReceiptType(String.valueOf(mCacheBeanList.get(position).getReceiptType()));
            cusRFIDEmergency.setReceiptTypeName(mCacheBeanList.get(position).getReceiptTypeName());
            cusRFIDEmergency.setReceiptRid(i + 1 + "");
            cusRFIDEmergency.setQty(list.get(i).getQty());
            cusRFIDEmergency.setEpcCode(list.get(i).getEpcCode());
            cusRFIDEmergency.setCusWhName(mCacheBeanList.get(position).getWhName());
            cusRFIDEmergency.setWhReal(mCacheBeanList.get(position).getWhCode());
            cusRFIDEmergency.setRemark(list.get(i).getLocationCode());
            listCo.add(cusRFIDEmergency);
        }
        RetrofitUtils.getRetrofit(EmergencyListActivity.this, "", "", "", "生成文件")
                .create(com.inossem.allotin.api.ApiService.class)
                .getFile(listCo)
                .enqueue(new com.inossem.allotin.utils.requestUtils.InossemNewsCallback<BaseObject<String>>() {
                    @Override
                    public void success(Response<BaseObject<String>> response) {
                        loadFile(response.body().getData(), position);
                    }
                });
    }

    //下载文件
    private void loadFile(String path, int position) {
//        String path = "https://pics4.baidu.com/feed/b58f8c5494eef01f362224a50a390f20bd317dec.png?token=47ce26dd8e4479ae47c9e5d0fddcba74&s=C0EA9A445C4530570684B4A10300A006";
        com.inossem.allotin.bl.DownloadBl downloadBl = new com.inossem.allotin.bl.DownloadBl(EmergencyListActivity.this);
        downloadBl.setDownloadDelegate(new com.inossem.allotin.bl.delegate.BLDelegate.DownLoadDelegate() {
            @Override
            public void onSuccess(File result) {
                com.inossem.allotin.utils.ToastUtils.showToast("文件下载成功");
                mCacheBeanList.get(position).setFileName("点击查看文件");
                mCacheBeanList.get(position).setFilePath(result.getAbsolutePath());
                mGreenDaoManager.updateCacheBean(mCacheBeanList);
                adapter.notifyDataSetChanged();
                openFile(result.getAbsolutePath());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                com.inossem.allotin.utils.ToastUtils.showToast("文件下载失败");
            }
        });
        String[] strs = path.split("/");
        downloadBl.downloadFile(com.inossem.allotin.constant.UrlConstant.DEFAULT_HTTP
                + com.inossem.allotin.constant.UrlConstant.DEFAULT_DOMAIN + ":"
                + com.inossem.allotin.constant.UrlConstant.DEFAULT_PORT
                + "/wms/web" + path, mCacheBeanList.get(position).getReceiptCode() + strs[strs.length - 1]);
    }

    private void openFile(String path) {
        try {
            Intent intent2 = new Intent("android.intent.action.VIEW");
            intent2.addCategory("android.intent.category.DEFAULT");
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(EmergencyListActivity.this, getApplicationContext().getPackageName() + ".provider", new File(path));
                intent2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//给目标文件临时授权，必需添加
            } else {
                uri = Uri.fromFile(new File(path));
            }
            //application/msword
            //application/vnd.ms-excel
            if (path.contains(".docx")) {
                intent2.setDataAndType(uri, "application/msword");
            } else if (path.contains(".xls")) {
                intent2.setDataAndType(uri, "application/vnd.ms-excel");
            } else {
                intent2.setDataAndType(uri, "text/plain");
            }
            startActivity(intent2);
        } catch (Exception e) {
            //没有安装第三方的软件会提示
            com.inossem.allotin.utils.ToastUtils.showToast("没有找到打开该文件的应用程序");
        }
    }

    private void applyPermission() {
        com.inossem.allotin.utils.PermissionUtils.applyForPermission(EmergencyListActivity.this, com.inossem.allotin.utils.PermissionUtils.getManifestPermission(EmergencyListActivity.this, com.inossem.allotin.utils.PermissionUtils.getAppProcessName(EmergencyListActivity.this)), new com.inossem.allotin.utils.PermissionUtils.OnApplyPermissionListener() {
            @Override
            public void onSuccessful() {
            }

            @Override
            public void onFailure() {
                com.inossem.allotin.utils.ToastUtils.showToast("由于您拒绝了某些权限,可能导致某些功能无法正常使用");
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK)
            switch (requestCode) {
                case com.inossem.allotin.utils.PermissionUtils.REQUEST_CODE_SETTING: {
                    if (com.inossem.allotin.utils.PermissionUtils.permissionIsAllow(EmergencyListActivity.this, com.inossem.allotin.utils.PermissionUtils.getManifestPermission(EmergencyListActivity.this, com.inossem.allotin.utils.PermissionUtils.getAppProcessName(EmergencyListActivity.this)))) {
//                        startActivity(intent);
//                        finish();
                    } else {
                        applyPermission();
                    }
                    break;
                }
            }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    /**
     * 刷新requestBean和Adapter
     */
    private void refresh() {
//        requestBean.setPageIndex(1);
        adapter.clearList();
    }

    /**
     * 请求数据
     */
    private void getData() {
        mCacheBeanList = mGreenDaoManager.getCacheBeanList(mWhCode, mReceiptType);
        tvInformation1.setText(mCacheBeanList.size() + "");
        adapter.clearList();
        adapter.addList(mCacheBeanList);
        showNoData();
    }

    private void showNoData() {
        if (adapter.getItemCount() <= 0) {
            includeNoData.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            includeNoData.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.cb_check, R.id.ll_recepit_type, R.id.ll_work_location, R.id.tv_delete, R.id.tv_add, R.id.settingImg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            // 全选
            case R.id.cb_check:
                for (CacheBean cacheBean : mCacheBeanList) {
                    cacheBean.setIsSelect(cbCheck.isChecked());
                }
                adapter.notifyDataSetChanged();
                break;
            // 单据类型
            case R.id.ll_recepit_type:
                com.inossem.allotin.utils.DialogUtils.getReceiptTypeDialog(this, listReceipt, "", new ReceiptTypeAdapter.OnChooseReceiptType() {
                    @Override
                    public void receiptTypeChoose(int receiptType, String receiptName) {
                        tvReceiptType.setText(receiptName);
                        mReceiptType = receiptType;
                        mReceiptTypeName = receiptName;
                        refresh();
                        getData();
                    }
                }).show();
                break;
            // 作业地点
            case R.id.ll_work_location:
                com.inossem.allotin.utils.DialogUtils.getRealWhCodeDialog(EmergencyListActivity.this, list, mWhCode, (typeCode, typeName, isCellEnabled) -> {
                    mWhCode = typeCode;
                    mWhName = typeName;
                    tvWorkLocation.setText(typeCode + "-" + typeName);
                    refresh();
                    getData();
                }).show();
                break;
            case R.id.tv_delete:
                com.inossem.allotin.utils.DialogUtils.getMsgDialog(EmergencyListActivity.this, new com.inossem.allotin.utils.DialogUtils.OnClickListener() {
                    @Override
                    public void onClickListener() {
                        for (CacheBean cacheBean : mCacheBeanList) {
                            if (cacheBean.getIsSelect()) {
                                com.inossem.allotin.utils.Utils.deleteFile(cacheBean.getFilePath()==null?"":cacheBean.getFilePath());
                                com.inossem.allotin.utils.Utils.deleteFile(cacheBean.getSignName());
                                mGreenDaoManager.delCacheBean(cacheBean.getId());
                            }
                        }
                        getData();
                        cbCheck.setChecked(false);
                    }
                }).show();
                break;
            case R.id.tv_add:
                Intent intent = new Intent(EmergencyListActivity.this, EmergencyDetailActivity.class);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.STATUS_CODE, com.inossem.allotin.constant.ItemStatusConstant.STATUS_CREATE);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.CUS_WH_SYS, mWhCode);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.CUS_WH_NAME, mWhName);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.RECEIPT_TYPE, mReceiptType);
                intent.putExtra(com.inossem.allotin.constant.ItemStatusConstant.RECEIPT_TYPE_NAME, mReceiptTypeName);
                startActivity(intent);
                break;
            case R.id.settingImg:
                startActivity(new Intent(EmergencyListActivity.this, BluetoothListActivity.class));
                break;
        }
    }
}
